<template>
  <Dialog title="上传文件" v-model="visible" top="10vh" @open="open">
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
      <el-form-item v-if="props?.query?.rightStatus === 1" label="群组成员" prop="userIds">
        <UserSelectButton v-model="selectedUsers" />
      </el-form-item>
      <el-form-item v-if="props?.query?.rightStatus === 1" label="群组可编辑" prop="editUserIds">
        <UserSelectButton v-model="selectedEditUser" />
      </el-form-item>
      <el-form-item label="附件" prop="fileList">
        <UploadFile
          ref="uploadRef"
          :file-type="['docx', 'pdf', 'jpg', 'png', 'jpeg', 'mp4']"
          :optionData="optionData"
          :autoUpload="false"
          @on-change="handleChange"
          @on-success="handleSuccess"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :loading="formLoading">确 定</el-button>
      <el-button @click="visible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { ResourceFileApi } from '@/api/school/resource'
const props: any = defineProps<{
  modelValue: boolean
  query?: object // 活动ID（主表的关联字段）
}>()
const emit = defineEmits(['update:modelValue', 'success'])
const visible = computed({
  get() {
    return props.modelValue
  },
  set(val) {
    emit('update:modelValue', val)
  }
})
const formLoading = ref(false)
const uploadRef: any = ref(null)
const formData: any = ref({
  fileList: []
})
const optionData: any = ref({
  uploadFileApi: ResourceFileApi.createResourceFiles,
  uploadParam: {}
})
const formRules = reactive({
  fileList: [{ required: true, message: '参与文件不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const selectedUsers = ref<any[]>([])
const selectedEditUser = ref<any[]>([])
const open = () => {
  selectedUsers.value = []
  selectedEditUser.value = []
  formData.value = {
    fileList: []
  }
}
const handleChange = (file: any, fileList: any) => {
  console.log(file, fileList, '---file')
  formData.value.fileList = fileList
}
const handleSuccess = () => {
  formLoading.value = false
  visible.value = false
  emit('success')
}
const submitForm = async () => {
  const userIds: any = selectedUsers.value?.map((user: any) => user.id)
  const editUserIds: any = selectedEditUser.value?.map((user: any) => user.id)
  optionData.value.uploadParam = { ...props.query, userIds, editUserIds }
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    await uploadRef.value?.uploadRef?.submit?.()
  } catch (error) {
  } finally {
    formLoading.value = false
  }
}
</script>
